package com.me.shop.order.action;



import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.me.shop.cart.bean.Cart;
import com.me.shop.cart.bean.CartItem;
import com.me.shop.order.bean.Order;
import com.me.shop.order.bean.OrderItem;
import com.me.shop.order.service.OrderService;
import com.me.shop.user.bean.User;
import com.me.shop.utils.PageBean;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class OrderAction extends ActionSupport implements ModelDriven<Order> {
	private Integer page;
	public void setPage(Integer page) {
		this.page = page;
	}

	private Order order = new Order();
	public Order getModel() {
		return order;
	}
	
	private OrderService orderService;
	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}
	
	public String save() {
		order.setOrdertime(new Date());
		order.setState(1); //1：未付款      2：付款单未发货     3：发货但未确认发货   4:完成交易
		Cart cart = (Cart) ServletActionContext.getRequest().getSession().getAttribute("cart");
		if(cart == null) {
			this.addActionMessage("还没有购物");
			return "msg";
		}
		order.setTotal(cart.getTotal());
		for (CartItem cartItem : cart.getCartItems()) {
			OrderItem orderItem = new OrderItem();
			orderItem.setCount(cartItem.getCount());
			orderItem.setSubtotal(cartItem.getSubtotal());
			orderItem.setProduct(cartItem.getProduct());
			orderItem.setOrder(order);
			
			order.getOrderItems().add(orderItem);
		}
		User existUser = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
		if(existUser == null) {
			this.addActionError("还没有登录~请先去登录");
			return "login";
		}
		order.setUser(existUser);
		orderService.save(order);
		return "saveSuccess";
	}
	
	public String findByUid() {
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
		PageBean<Order> pageBean = orderService.findByPageUid(user.getUid(), page);
		ActionContext.getContext().getValueStack().set("pageBean", pageBean);
		return "findByUidSuccess";
	}
	
	public String findByOid() {
		order = orderService.findByOid(order.getOid());
		return "findByOidSuccess";
	}
	
}




















